#  Copyright 2011 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import re


class Records(object):

    search_regs = re.compile(r'^-record\((.*?)\)\.', re.MULTILINE | re.DOTALL)
    parse_rec = re.compile(r'\'(.*?)\',\{\n(.*?)\}', re.MULTILINE | re.DOTALL)
    find_fields = re.compile(r"\s*'?(.+?)'?(?:\s=.*?)?(?:,|$)")

    def __init__(self, records):
        self._recs = {} 
        for match in self.search_regs.finditer(records):
            self._parse_record(match.group(0))

    def _parse_record(self, record):
        (name, fields) = self.parse_rec.search(record).groups()
        self._recs[name] = self._parse_fields(fields)

    def _parse_fields(self, fields):
        return self.find_fields.findall(fields)

    def __getitem__(self, key):
        return self._recs[key]

    def __contains__(self, item):
        return item in self._recs

